package com.erp.erp_ui.ProductMainInfo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.erp.erp_entitys.Dictionary.DictionaryEntity;
import com.erp.erp_entitys.ProducFjInfo.ProducFjInfoEntity;
import com.erp.erp_entitys.ProducFjInfo.ProducFjInfoExample;
import com.erp.erp_entitys.ProducWj.ProducWjEntity;
import com.erp.erp_entitys.ProducWj.ProducWjExample;
import com.erp.erp_entitys.ProductBoxGauge.ProductBoxGauge;
import com.erp.erp_entitys.ProductCatalog.ProductCatalogEntity;
import com.erp.erp_entitys.ProductFjGe.ProductFjGeEntity;
import com.erp.erp_entitys.ProductFjGe.ProductFjGeExample;
import com.erp.erp_entitys.ProductFjGysBak.ProductFjGysBakEntity;
import com.erp.erp_entitys.ProductFjGysBak.ProductFjGysBakExample;
import com.erp.erp_entitys.ProductImg.ProductImgEntity;
import com.erp.erp_entitys.ProductImg.ProductImgExample;
import com.erp.erp_entitys.ProductMainInfo.ProductMainInfoBjVoEntity;
import com.erp.erp_entitys.ProductMainInfo.ProductMainInfoEntity;
import com.erp.erp_entitys.ProductMainInfo.ProductMainInfoExample;
import com.erp.erp_entitys.ProductMainInfo.ProductMainInfoVoEntity;
import com.erp.erp_entitys.ProductMainInfo.Req.*;
import com.erp.erp_entitys.ProductMainInfo.Res.*;
import com.erp.erp_entitys.ProductPriceRange.ProductPriceRange;
import com.erp.erp_entitys.User.UserEntity;
import com.erp.erp_servers.Dictionary.IDictionary2Service;
import com.erp.erp_servers.ProducFjInfo.IProductFjInfoService;
import com.erp.erp_servers.ProducWj.IProductWjService;
import com.erp.erp_servers.ProductBoxGauge.IProductBoxGaugeService;
import com.erp.erp_servers.ProductCatalog.IProductCatalogService;
import com.erp.erp_servers.ProductFjGe.IProductFjGeService;
import com.erp.erp_servers.ProductFjGysBak.IProductFjGysBakService;
import com.erp.erp_servers.ProductImg.IProductImgService;
import com.erp.erp_servers.ProductLog.IProductLogService;
import com.erp.erp_servers.ProductMainInfo.IProductMainInfoService;
import com.erp.erp_servers.ProductPriceRange.IProductPriceRangeService;
import com.erp.erp_servers.warehouse.IStockService;
import com.erp.erp_ui.ProductMainInfo.req.ProductMargeReq;
import com.erp.erp_ui.ProductMainInfo.req.SpecMargeReq;
import com.erp.erp_ui.ProductMainInfo.service.productMainInfoAllService;
import com.erp.erp_ui.ProductMainInfo.vo.ProductMargeInfoVo;
import com.erp.erp_ui.ProductMainInfo.vo.SupplierPriceVo;
import com.erp.erp_ui.base.Base;
import com.erp.utils.DateUtils;
import com.erp.utils.R;
import com.erp.utils.ResultStatusEnum;
import com.erp.utils.StringUtil;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName OperationLogControl
 * @Description 产品主信息
 * @Author songjizhen
 * @Date 2020-06-30 21:41
 * @Version 1.0
 */
@Controller
@RequestMapping(value = "productmaininfo")
public class ProductMainInfoControl extends Base {
    @Autowired
    IProductMainInfoService productMainInfoService;
    @Autowired
    IProductImgService productImgService;
    @Autowired
    IProductWjService productWjService;
    @Autowired
    IDictionary2Service dictionary2Service;
    @Autowired
    IProductLogService productLogService;
    @Autowired
    IProductCatalogService productCatalogService;
    @Autowired
    IProductFjInfoService productFjInfoService;
    @Autowired
    IProductFjGeService productFjGeService;
    @Autowired
    productMainInfoAllService productMainInfoAllService;
    @Autowired
    IProductFjGysBakService productFjGysBakService;
    @Autowired
    IProductBoxGaugeService productBoxGaugeService;
    @Autowired
    IProductPriceRangeService productPriceRangeService;
    @Autowired
    IStockService stockService;
    /**
     * 根据产品目录获取产品列表
     * @param cataCode
     * @return
     */
    @RequestMapping(value = "selectByPage")
    @ResponseBody
    public R<List<ProductMainInfoVoEntity>> selectByPage(String cataCode,String code,String chinaName,String englishName,String gecode,String ge,String upCataCodePath,String  chineseDesc,String  englishDesc){
//        System.out.println(cataCode);
        try{
//            List<String> cataCodeList = JSON.parseArray(cataCode, String.class);

            //cataCode=this.conver(cataCode);
//            code=this.conver(code);
//            chinaName=this.conver(chinaName);
//            englishName=this.conver(englishName);
//            gecode=this.conver(gecode);
//            ge=this.conver(ge);
//            upCataCodePath=this.conver(upCataCodePath);
//            chineseDesc=this.conver(chineseDesc);
//            englishDesc=this.conver(englishDesc);

           // cataCode="dd";
//            List<ProductMainInfoVoEntity> list=new ArrayList<>();
           // list=productMainInfoService.getVoByCatalog(cataCode);
//            ProductMainInfoExample example=new ProductMainInfoExample();
//            ProductMainInfoExample.Criteria criteria = example.createCriteria();
//            if(cataCode !=null) {
//                criteria.andCataCodeIn(cataCodeList);
               // criteria.andCataCodeIn(getCatalogBycode(cataCode));
               // criteria.andCataCodeEqualTo(cataCode);
//            }
           /* else{
                List<String> list2=new ArrayList<>();
                list2.add("3");
                list2.add("4");
                criteria.andCataCodeNotIn(list2);
            }*/
//            if(code !=null) criteria.andCodeLike("%"+code+"%");
//            if(chinaName !=null) criteria.andChinaNameLike("%"+chinaName+"%");
//            if(englishName !=null) criteria.andEnglishNameLike("%"+englishName+"%");
//            if(gecode !=null) criteria.andGecodeLike("%"+gecode+"%");
//            if(ge !=null) criteria.andGeLike("%"+ge+"%");
//            if (upCataCodePath!=null) criteria.andUpCataCodeLike("%"+upCataCodePath+"%");
//            List<ProductMainInfoEntity> productMainInfoEntities = productMainInfoService.selectByExample(example);
            ProductMainInfoReq req=new ProductMainInfoReq();
            req.setCataCode(cataCode);
            req.setChinaName(chinaName);
            req.setEnglishName(englishName);
            req.setCode(code);
            req.setGe(ge);
            req.setGecode(gecode);
            req.setChineseDesc(chineseDesc);
            req.setEnglishDesc(englishDesc);
            List<ProductMainInfoEntity> productMainInfoEntities = productMainInfoService.findProductMainInfo(req);


            R<List<ProductMainInfoEntity>> build = R.build(productMainInfoEntities);

            List<ProductMainInfoVoEntity> list=new ArrayList<>();

            for(int i=0;i<productMainInfoEntities.size();i++){
                ProductMainInfoVoEntity pmve=new ProductMainInfoVoEntity();
                list.add(pmve.conver(productMainInfoEntities.get(i)));
            }


            R<List<ProductMainInfoVoEntity>> rp = R.build(list);
            rp.setCount(build.getCount());
            rp.setTotal(build.getTotal());

            //取当前页所有产品的图片
            List<String> listcodes=new ArrayList<>();
            for(int i=0;i<productMainInfoEntities.size();i++){
                listcodes.add(productMainInfoEntities.get(i).getCode());
            }
            //取海关编码
            List<DictionaryEntity> hs = this.getHS();
            ProductImgExample exampleimg=new ProductImgExample();
            ProductImgExample.Criteria criteria1 = exampleimg.createCriteria();
            criteria1.andProductCodeIn(listcodes);
            List<ProductImgEntity> productImgEntities = new ArrayList<>();
            if(listcodes.size()>0)productImgEntities = productImgService.selectByExample(exampleimg);
            String pcode="";
            String hscode="";
            for(int i=0;i<rp.getData().size();i++){
                if(! rp.getData().get(i).getCode().equals(pcode)){
                    pcode=rp.getData().get(i).getCode();

                    for(int n=0;n<productImgEntities.size();n++){
                        if(pcode.equals(productImgEntities.get(n).getProductCode())){
                            rp.getData().get(i).setImg(productImgEntities.get(n).getImg());
                            break;
                        }
                    }
                }
                if (StringUtils.isNotEmpty(rp.getData().get(i).getHgCode())){
                    if(!rp.getData().get(i).getHgCode().equals(hscode)){
                        hscode=rp.getData().get(i).getHgCode();
                        for(int n=0;n<hs.size();n++){
                            if(hscode.equals(hs.get(n).getCode())){
                                rp.getData().get(i).setImportTariff(hs.get(n).getImportTariff());
                                rp.getData().get(i).setTaxRate(hs.get(n).getTaxRate());
                                break;
                            }
                        }
                    }
                }

            }

            return rp;
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }
    @RequestMapping(value = "selectBjByPage")
    @ResponseBody
    public R<List<ProductMainInfoBjVoEntity>> selectBjByPage(String cataCode, String code, String chinaName, String englishName, String gecode, String ge,Integer deactivateType){
        try{
            List<String> cataCodeList = JSON.parseArray(cataCode, String.class);
            //cataCode=this.conver(cataCode);
            code=this.conver(code);
            chinaName=this.conver(chinaName);
            englishName=this.conver(englishName);
            gecode=this.conver(gecode);
            ge=this.conver(ge);
            // cataCode="dd";
            List<ProductMainInfoVoEntity> list=new ArrayList<>();
            // list=productMainInfoService.getVoByCatalog(cataCode);
            ProductMainInfoExample example=new ProductMainInfoExample();
            ProductMainInfoExample.Criteria criteria = example.createCriteria();
            if(cataCodeList.size()>0) {
                criteria.andCataCodeIn(cataCodeList);
                /////////////////////////////////////////////////
            }
           /* else{
                List<String> list2=new ArrayList<>();
                list2.add("3");
                list2.add("4");
                criteria.andCataCodeNotIn(list2);
            }*/
            if(code !=null) criteria.andCodeLike("%"+code+"%");
            if(chinaName !=null) criteria.andChinaNameLike("%"+chinaName+"%");
            if(englishName !=null) criteria.andEnglishNameLike("%"+englishName+"%");
            if(gecode !=null) criteria.andGecodeLike("%"+gecode+"%");
            if(ge !=null) criteria.andGeLike("%"+ge+"%");

            if (deactivateType!=null) criteria.andDeactivateTypeEqualTo(deactivateType);

            List<ProductMainInfoEntity> productMainInfoEntities = productMainInfoService.selectByExample(example);
            for(int i=0;i<productMainInfoEntities.size();i++){
                ProductMainInfoVoEntity pmve=new ProductMainInfoVoEntity();
                list.add(pmve.conver(productMainInfoEntities.get(i)));
            }
            R<List<ProductMainInfoEntity>> build = R.build(productMainInfoEntities);

            R<List<ProductMainInfoVoEntity>> rp = R.build(list);
            rp.setCount(build.getCount());
            rp.setTotal(build.getTotal());

            //取当前页所有产品的图片
            List<String> listcodes=new ArrayList<>();
            for(int i=0;i<productMainInfoEntities.size();i++){
                listcodes.add(productMainInfoEntities.get(i).getCode());
            }
            //取海关编码
            List<DictionaryEntity> hs = this.getHS();
            ProductImgExample exampleimg=new ProductImgExample();
            ProductImgExample.Criteria criteria1 = exampleimg.createCriteria();
            criteria1.andProductCodeIn(listcodes);
            List<ProductImgEntity> productImgEntities = new ArrayList<>();
            if(listcodes.size()>0)productImgEntities = productImgService.selectByExample(exampleimg);
            String pcode="";
            String hscode="";
            for(int i=0;i<rp.getData().size();i++){
                if(! rp.getData().get(i).getCode().equals(pcode)){
                    pcode=rp.getData().get(i).getCode();

                    for(int n=0;n<productImgEntities.size();n++){
                        if(pcode.equals(productImgEntities.get(n).getProductCode())){
                            rp.getData().get(i).setImg(productImgEntities.get(n).getImg());
                            break;
                        }
                    }
                }
                if(!rp.getData().get(i).getHgCode().equals(hscode)){
                    hscode=rp.getData().get(i).getHgCode();
                    for(int n=0;n<hs.size();n++){
                        if(hscode.equals(hs.get(n).getCode())){
                            rp.getData().get(i).setImportTariff(hs.get(n).getImportTariff());
                            rp.getData().get(i).setTaxRate(hs.get(n).getTaxRate());
                            break;
                        }
                    }
                }
            }
            //R<List<ProductMainInfoVoEntity>> rp = R.build(list);
            /*R<List<ProductMainInfoVoEntity>> rp = R.build(list);
            rp.setCount(build.getCount());
            rp.setTotal(build.getTotal());*/

            ProducFjInfoExample examplefj=new ProducFjInfoExample();
            ProducFjInfoExample.Criteria criteria2 = examplefj.createCriteria();
            //criteria2.andProductCodeEqualTo(code);
            criteria2.andProductCodeIn(listcodes);
            //部件信息
            List<ProducFjInfoEntity> producFjInfoEntities = productFjInfoService.selectByExample(examplefj);
            List<ProductMainInfoBjVoEntity> listfj=new ArrayList<>();
            List<ProductMainInfoVoEntity> data = rp.getData();//主信息
            for(int n=0;n<producFjInfoEntities.size();n++){
                ProductMainInfoBjVoEntity pbj=new ProductMainInfoBjVoEntity();
                ProducFjInfoEntity producFjInfoEntity = producFjInfoEntities.get(n);
                pbj.setGecode(producFjInfoEntity.getCode());
                pbj.setGe(producFjInfoEntity.getGe());
                pbj.setBzsm(producFjInfoEntity.getBzsm());
                pbj.setCpjz(producFjInfoEntity.getCpjz());
                pbj.setCpmz(producFjInfoEntity.getCpmz());
                    for(int i=0;i<data.size();i++){
                        if(data.get(i).getCode().equals(producFjInfoEntity.getProductCode())){
                            pbj.setImg(data.get(i).getImg());
                            pbj.setId(data.get(i).getId());
                            pbj.setCode(data.get(i).getCode());
                            pbj.setChinaName(data.get(i).getChinaName());
                            pbj.setEnglishName(data.get(i).getEnglishName());
                            pbj.setHgCode(data.get(i).getHgCode());
                            pbj.setTaxRate(data.get(i).getTaxRate());
                            pbj.setImportTariff(data.get(i).getImportTariff());
                        }
                    }
                listfj.add(pbj);
            }
            R<List<ProductMainInfoBjVoEntity>> rbj= R.build(listfj);
            rbj.setTotal(rp.getTotal());
            rbj.setCount(rp.getCount());
            rbj.setStatus(rp.getStatus());
            rbj.setMsg(rp.getMsg());
            rbj.setCode(rp.getCode());
            return rbj;
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }
    private List<DictionaryEntity> getHS(){
        List<DictionaryEntity> value= dictionary2Service.getValue(3, 8);
        List<DictionaryEntity> list=new ArrayList<DictionaryEntity>();
        for(int i=0;i<value.size();i++){
            DictionaryEntity de = value.get(i);
            if(de.getCode() !=null){
                list.add(de);
            }
        }
        return list;
    }

    /**
     * 根据主键删除产品
     * @param ids
     * @return
     */
    @RequestMapping(value = "delproduct",method = RequestMethod.POST)
    @ResponseBody
    public R<Integer> delproduct(  String[] ids){
        try{
            UserEntity user = (UserEntity)this.getBean("user");
            List<Integer> list=new ArrayList<>();
            for(int i=0;i<ids.length;i++){
                list.add(Integer.parseInt(ids[i].replace("[","").replace("]","")));
            }
            ProductMainInfoExample example=new ProductMainInfoExample();
            ProductMainInfoExample.Criteria criteria = example.createCriteria();
            criteria.andIdIn(list);

            List<ProductMainInfoEntity> productMainInfoEntities = productMainInfoService.selectByExample(example);
            ProductMainInfoEntity pme=productMainInfoEntities.get(0);
            int num=0;
            //垃圾箱中彻底删除
            if(pme.getCataCode().equals("4")){
                List<String> listpp=new ArrayList<>();
                for(int i=0;i<list.size();i++){
                    ProductMainInfoEntity pp = productMainInfoService.selectByPrimaryKey(list.get(i));
                    listpp.add(pp.getCode());
                }
                 num = productMainInfoService.deleteByExample(example);
                if(num>0){

                    ProducFjInfoExample fjInfoExample=new ProducFjInfoExample();
                    ProducFjInfoExample.Criteria fjInfoCriteria = fjInfoExample.createCriteria();
                    fjInfoCriteria.andProductCodeIn(listpp);
                    List<ProducFjInfoEntity> fjInfoEntities = productFjInfoService.selectByExample(fjInfoExample);

                    for (ProducFjInfoEntity p:fjInfoEntities) {
                        //删除产品规格配件
                        ProductFjGeExample fjGeExample=new ProductFjGeExample();
                        ProductFjGeExample.Criteria fjGeCriteria = fjGeExample.createCriteria();
                        fjGeCriteria.andZhugeEqualTo(p.getCode());
                        fjGeCriteria.andMainProductCodeEqualTo(p.getProductCode());
                        productFjGeService.deleteByExample(fjGeExample);

                        //删除产品备选供应商
                        ProductFjGysBakExample fjGysBakExample=new ProductFjGysBakExample();
                        ProductFjGysBakExample.Criteria fjGysBakCriteria = fjGysBakExample.createCriteria();
                        fjGysBakCriteria.andFjCodeEqualTo(p.getCode());
                        fjGeCriteria.andProductCodeEqualTo(p.getProductCode());
                        productFjGysBakService.deleteByExample(fjGysBakExample);

                        //删除产品箱规
                        ProductBoxGauge boxGauge=new ProductBoxGauge();
                        boxGauge.setSpecificationCode(p.getCode());
                        boxGauge.setProductCode(p.getProductCode());
                        productBoxGaugeService.deleteByParam(boxGauge);

                        //删除区间价格
                        ProductPriceRange priceRange=new ProductPriceRange();
                        priceRange.setProductCode(p.getProductCode());
                        priceRange.setSpecificationCode(p.getCode());
                        productPriceRangeService.deleteByParam(priceRange);
                    }
                    //删除产品规格
                    productFjInfoService.deleteByExample(fjInfoExample);



                    for(int i=0;i<listpp.size();i++){
                        productLogService.savelog(listpp.get(i),"删除","从回收箱删除",user.getName(),user.getCode());
                    }
                }
            }
            //由垃圾箱进回收箱
            if(pme.getCataCode().equals("3")){
                ProductMainInfoEntity record=new ProductMainInfoEntity();
                for(int i=0;i<list.size();i++){
                    record.setId(list.get(i));
                        record.setCataCode("4");
                        num = productMainInfoService.updateByPrimaryKeySelective(record);

                    ProductMainInfoEntity pp = productMainInfoService.selectByPrimaryKey(list.get(i));
                    productLogService.savelog(pp.getCode(),"删除","删除到回收箱",user.getName(),user.getCode());
                }
            }
            //由正常进垃圾箱
            if(!pme.getCataCode().equals("3") && !pme.getCataCode().equals("4")){
                ProductMainInfoEntity record=new ProductMainInfoEntity();
                for(int i=0;i<list.size();i++){
                    record.setId(list.get(i));
                    record.setCataCode("3");
                    num = productMainInfoService.updateByPrimaryKeySelective(record);

                    ProductMainInfoEntity pp = productMainInfoService.selectByPrimaryKey(list.get(i));
                    productLogService.savelog(pp.getCode(),"删除","删除到垃圾箱",user.getName(),user.getCode());
                }
            }


            return R.build(num);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 从垃圾箱或回收箱恢复
     * @param ids
     * @return
     */
    @RequestMapping(value = "hf",method = RequestMethod.POST)
    @ResponseBody
    public R<Integer> hf(String[] ids){
        try{
            UserEntity user = (UserEntity)this.getBean("user");
            //根据主键获取一条主信息
            List<Integer> list=new ArrayList<>();
            for(int i=0;i<ids.length;i++){
                list.add(Integer.parseInt(ids[i].replace("[","").replace("]","")));
            }
            ProductMainInfoExample example=new ProductMainInfoExample();
            ProductMainInfoExample.Criteria criteria = example.createCriteria();
            criteria.andIdIn(list);
            List<ProductMainInfoEntity> productMainInfoEntities = productMainInfoService.selectByExample(example);
            ProductMainInfoEntity pme=productMainInfoEntities.get(0);

            //判断当前是垃圾箱还是回收箱
            //4：回收箱；3：垃圾箱）
            ProductMainInfoEntity record=new ProductMainInfoEntity();
            Integer num=0;
            for(int i=0;i<list.size();i++){
                record.setId(list.get(i));
                if(pme.getCataCode().equals("4")  ){
                    record.setCataCode("3");
                }
                if( pme.getCataCode().equals("3")){
                    record.setCataCode("1");
                }
                num = productMainInfoService.updateByPrimaryKeySelective(record);

                if(num >0){
                    ProductMainInfoEntity pp = productMainInfoService.selectByPrimaryKey(list.get(i));
                    productLogService.savelog(pp.getCode(),"恢复","从回收箱或垃圾箱中恢复产品",user.getName(),user.getCode());
                }

            }


            return R.build(num);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 保存主信息
     * @param pmve
     * @return
     */
    @RequestMapping(value = "savemain",method = RequestMethod.POST)
    @ResponseBody
    public R<Integer> savemain(@RequestBody ProductMainInfoVoEntity pmve){
        try{
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            UserEntity user = (UserEntity)this.getBean("user");
            String imgs=pmve.getImg();
            String wjs=pmve.getWj();
            List img = (List) JSON.parse(imgs);
            List wj = (List) JSON.parse(wjs);
            if(pmve.getId() !=null){

                pmve.setGecode(sdf.format(new Date()));
                //更新
                this.updateMain(pmve);
                productLogService.savelog(pmve.getCode(),"更新","更新了产品主信息，产品："+pmve.getChinaName(),user.getName(),user.getCode());

                //如果更新配件,则同步更新配件信息
                if(2 == pmve.getProductType()){
                    ProductFjGeExample example = new ProductFjGeExample();
                    ProductFjGeExample.Criteria criteria = example.createCriteria();
                    criteria.andProductCodeEqualTo(pmve.getCode());
                    List<ProductFjGeEntity> productFjGeEntities = productFjGeService.selectByExample(example);
                    if(!CollectionUtils.isEmpty(productFjGeEntities)){
                        //循环更新配件信息
                        for(ProductFjGeEntity parts : productFjGeEntities){
                            ProductFjGeEntity updateReq = new ProductFjGeEntity();
                            updateReq.setId(parts.getId());
                            updateReq.setChinaname(pmve.getChinaName());
                            updateReq.setEnglishname(pmve.getEnglishName());
                            productFjGeService.updateByPrimaryKeySelective(updateReq);
                        }
                    }
                }

                //删除图片及文件
                ProductImgExample exampleIMG=new ProductImgExample();
                ProductImgExample.Criteria criteria = exampleIMG.createCriteria();
                criteria.andProductCodeEqualTo(pmve.getCode());
                productImgService.deleteByExample(exampleIMG);

                ProducWjExample exampleWJ=new ProducWjExample();
                ProducWjExample.Criteria criteria1 = exampleWJ.createCriteria();
                criteria1.andProductCodeEqualTo(pmve.getCode());
                productWjService.deleteByExample(exampleWJ);

                ProductMainInfoEntity pme = (ProductMainInfoEntity) pmve;
                //存图片

                    ProductImgEntity imgrecord = new ProductImgEntity();
                    imgrecord.setProductCode(pme.getCode());
                    for (int i = 0; i < img.size(); i++) {
                        imgrecord.setImg(img.get(i).toString());
                        productImgService.insertSelective(imgrecord);
                    }

                //存文件

                    ProducWjEntity pwe = new ProducWjEntity();
                    pwe.setProductCode(pme.getCode());
                    for (int i = 0; i < wj.size(); i++) {
                        pwe.setPath(wj.get(i).toString());
                        productWjService.insertSelective(pwe);
                    }



                return R.build(1);
            }else {
                //新增
                ProductMainInfoEntity pme = (ProductMainInfoEntity) pmve;
                 pme.setGe(sdf.format(new Date()));
           /* if(this.isexit(pme.getCode())){
                pme.setCode(System.currentTimeMillis()+"");
            }*/
                int num = productMainInfoService.insertSelective(pme);
                //存图片
                if (num > 0) {
                    ProductImgEntity imgrecord = new ProductImgEntity();
                    imgrecord.setProductCode(pme.getCode());
                    for (int i = 0; i < img.size(); i++) {
                        imgrecord.setImg(img.get(i).toString());
                        productImgService.insertSelective(imgrecord);
                    }
                }
                //存文件
                if (num > 0) {
                    ProducWjEntity pwe = new ProducWjEntity();
                    pwe.setProductCode(pme.getCode());
                    for (int i = 0; i < wj.size(); i++) {
                        pwe.setPath(wj.get(i).toString());
                        productWjService.insertSelective(pwe);
                    }

                }
                if (num > 0) {
                    productLogService.savelog(pmve.getCode(), "新增", "新增了产品主信息，产品：" + pmve.getChinaName(), user.getName(), user.getCode());
                }
                num = this.getIdByCode(pme.getCode());

                return R.build(num);
            }
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }
    private int updateMain(ProductMainInfoVoEntity pmve){
        UserEntity user = (UserEntity)this.getBean("user");
        String imgs=pmve.getImg();
        String wjs=pmve.getWj();
        List img = (List) JSON.parse(imgs);
        List wj = (List) JSON.parse(wjs);
        ProductMainInfoEntity pme=(ProductMainInfoEntity)pmve;

       /* if(this.isexit(pme.getCode())){
            pme.setCode(System.currentTimeMillis()+"");
        }*/
        int num = productMainInfoService.updateByPrimaryKeySelective(pme);
        //存图片
        if(num >0){
            ProductImgEntity imgrecord=new ProductImgEntity();
            imgrecord.setProductCode(pme.getCode());

            ProductImgExample example=new ProductImgExample();
            ProductImgExample.Criteria criteria = example.createCriteria();
            criteria.andProductCodeEqualTo(pme.getCode());
            //if (img.size()>0){
                productImgService.deleteByExample(example);
            //}
            for(int i=0;i<img.size();i++){
                imgrecord.setImg(img.get(i).toString());
                productImgService.insertSelective(imgrecord);
            }
        }
        //存文件
        if(num >0){
            ProducWjEntity pwe=new ProducWjEntity();
            pwe.setProductCode(pme.getCode());

            ProducWjExample example=new ProducWjExample();
            ProducWjExample.Criteria criteria = example.createCriteria();
            criteria.andProductCodeEqualTo(pme.getCode());
            //if (wj.size()>0){
                productWjService.deleteByExample(example);
           // }
            for(int i=0;i<wj.size();i++){
                pwe.setPath(wj.get(i).toString());
                productWjService.insertSelective(pwe);
            }

        }
        return num;
    }
    @RequestMapping(value = "isexit")
    @ResponseBody
    public  R<Boolean> isexit(String code){
        ProductMainInfoEntity pme=new ProductMainInfoEntity();
        ProductMainInfoExample example=new ProductMainInfoExample();
        ProductMainInfoExample.Criteria criteria = example.createCriteria();
        criteria.andCodeEqualTo(code);
        List<ProductMainInfoEntity> productMainInfoEntities = productMainInfoService.selectByExample(example);
        return  R.build(productMainInfoEntities.size()==0?false:true);
       
    }
    private Integer getIdByCode(String code){
        ProductMainInfoEntity pme=new ProductMainInfoEntity();
        ProductMainInfoExample example=new ProductMainInfoExample();
        ProductMainInfoExample.Criteria criteria = example.createCriteria();
        criteria.andCodeEqualTo(code);
        List<ProductMainInfoEntity> productMainInfoEntities = productMainInfoService.selectByExample(example);
        return productMainInfoEntities.get(0).getId();
    }

    /**
     * 根据id获取主信息
     * @param id
     * @return
     */
    @RequestMapping(value = "queryById")
    @ResponseBody
    public R<ProductMainInfoVoEntity> queryById(Integer id){
        try{
            ProductMainInfoExample example=new ProductMainInfoExample();
            ProductMainInfoExample.Criteria criteria = example.createCriteria();
            criteria.andIdEqualTo(id);
            List<ProductMainInfoEntity> productMainInfoEntities = productMainInfoService.selectByExample(example);
            ProductMainInfoEntity pme=productMainInfoEntities.get(0);

            ProductMainInfoVoEntity pmve=new ProductMainInfoVoEntity();
            pmve=pmve.conver(pme);

            //根据目录编码获取目录名称,并连接父目录名称
            ProductCatalogEntity catalogEntity = productCatalogService.selectByPrimary(pmve.getCataCode());
            if (catalogEntity!=null){
                ProductCatalogEntity catalogEntityP = productCatalogService.selectByPrimaryKey(catalogEntity.getPid());
                if (catalogEntityP!=null){
                    pmve.setCataCodeNameCombine(catalogEntity.getName()+"_"+catalogEntityP.getName());
                }else {
                    pmve.setCataCodeNameCombine(catalogEntity.getName());
                }
            }



            String code=pmve.getCode();
            //取图片与文件列表
            ProductImgExample exampleimg=new ProductImgExample();
            ProductImgExample.Criteria criteria1 = exampleimg.createCriteria();
            criteria1.andProductCodeEqualTo(code);
            List<ProductImgEntity> productImgEntities = productImgService.selectByExample(exampleimg);
            List<String> img=new ArrayList<>();
            for(int i=0;i<productImgEntities.size();i++){
                img.add(productImgEntities.get(i).getImg());
            }
            List<String> wj=new ArrayList<>();
            ProducWjExample examplewj=new ProducWjExample();
            ProducWjExample.Criteria criteria2 = examplewj.createCriteria();
            criteria2.andProductCodeEqualTo(code);
            List<ProducWjEntity> producWjEntities = productWjService.selectByExample(examplewj);
            for(int i=0;i<producWjEntities.size();i++){
                wj.add(producWjEntities.get(i).getPath());
            }

            pmve.setImg(JSON.toJSONString(img));
            pmve.setWj(JSON.toJSONString(wj));

            return R.build(pmve);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 产品合并
     *
     * @param req 合并信息
     * @return 合并后的数据
     */
    @PostMapping("/getMargeData")
    @ResponseBody
    public R getMargeData(@RequestBody ProductMargeReq req) {
        try {
            //初始化回参对象
            ProductMargeInfoVo vo = new ProductMargeInfoVo();
            if (null == req.getId() || StringUtils.isEmpty(req.getSpecCode()) || CollectionUtils.isEmpty(req.getSpecMargeList())) {
                return R.build(vo);
            }
            //1.获取合并的产品信息
            ProductMainInfoVoEntity mainInfoVo = getMainInfoVo(req.getId(), req.getSpecCode(), vo);
            //获取供应商及供应商最高价信息
            getSupplierInfo(req.getProductCode(), req.getSpecCode(), vo);
            //产品编码集合
            List<String> codeList = new ArrayList<>();
            //主产品编码
            String productCode = mainInfoVo.getCode();
            codeList.add(productCode);
            //合并后新的产品编码(产品编码-配件编码)
            String newProductCode = mainInfoVo.getCode();
            //循环获取被合并的配件信息
            for (SpecMargeReq specMarge : req.getSpecMargeList()) {
                ProductMainInfoVoEntity mainInfoPartsVo = getMainInfoVo(specMarge.getPartsId(), specMarge.getPartsSpec(), vo);
                //产品编码组合
                newProductCode = newProductCode + "-" + mainInfoPartsVo.getCode();
                codeList.add(mainInfoPartsVo.getCode());
                //获取供应商及供应商最高价信息
                getSupplierInfo(specMarge.getPartsProductCode(), specMarge.getPartsSpec(), vo);
            }
            //新的产品编码
            mainInfoVo.setCode(newProductCode);
            //获取图片和文件
            getImgAndFile(mainInfoVo, codeList);
            //主产品信息
            vo.setMainInfo(mainInfoVo);

            //2.获取合并的规格信息
            getSpecInfo(vo, req);

            return R.build(vo);
        } catch (Exception e) {
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }

    /**
     * 产品合并并保存
     *
     * @param req 合并信息
     * @return 合并后的数据
     */
    @PostMapping("/getMargeAndSaveData")
    @ResponseBody
    public R getMargeAndSaveData(@RequestBody ProductMargeReq req) {
        try {
            //初始化回参对象
            ProductMargeInfoVo vo = new ProductMargeInfoVo();
            if (null == req.getId() || StringUtils.isEmpty(req.getSpecCode()) || CollectionUtils.isEmpty(req.getSpecMargeList())) {
                return R.build(vo);
            }
            //1.获取合并的产品信息
            ProductMainInfoVoEntity mainInfoVo = getMainInfoVo(req.getId(), req.getSpecCode(), vo);
            //获取供应商及供应商最高价信息
            getSupplierInfo(req.getProductCode(), req.getSpecCode(), vo);
            //产品编码集合
            List<String> codeList = new ArrayList<>();
            //主产品编码
            String productCode = mainInfoVo.getCode();
            codeList.add(productCode);
            //合并后新的产品编码(产品编码-配件编码)
            String newProductCode = mainInfoVo.getCode();
            //循环获取被合并的配件信息
            for (SpecMargeReq specMarge : req.getSpecMargeList()) {
                ProductMainInfoVoEntity mainInfoPartsVo = getMainInfoVo(specMarge.getPartsId(), specMarge.getPartsSpec(), vo);
                //产品编码组合
                newProductCode = newProductCode + "-" + mainInfoPartsVo.getCode();
                codeList.add(mainInfoPartsVo.getCode());
                //获取供应商及供应商最高价信息
                getSupplierInfo(specMarge.getPartsProductCode(), specMarge.getPartsSpec(), vo);
            }
            //新的产品编码
            mainInfoVo.setCode(newProductCode);
            //获取图片和文件
            getImgAndFile(mainInfoVo, codeList);
            //主产品信息
            vo.setMainInfo(mainInfoVo);

            //2.获取合并的规格信息
            getSpecInfo(vo, req);

            //3.保存主产品信息
            ProductMainInfoEntity mainInfoQuery = new ProductMainInfoEntity();
            //字段赋值
            BeanUtils.copyProperties(mainInfoVo, mainInfoQuery);
            //产品目录默认为:CPMU001
            mainInfoQuery.setCataCode("CPMU001");
            //产品类型:成品
            mainInfoQuery.setProductType(1);
            //创建时间
            mainInfoQuery.setGe(DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
            int num = productMainInfoService.insertSelective(mainInfoQuery);
            if (num > 0) {
                //存图片
                ProductImgEntity imgrecord = new ProductImgEntity();
                imgrecord.setProductCode(mainInfoQuery.getCode());
                List<String> img = mainInfoVo.getImgList();
                if(!CollectionUtils.isEmpty(img)){
                    for (int i = 0; i < img.size(); i++) {
                        imgrecord.setImg(img.get(i));
                        productImgService.insertSelective(imgrecord);
                    }
                }

                //存文件
                ProducWjEntity pwe = new ProducWjEntity();
                pwe.setProductCode(mainInfoQuery.getCode());
                List<String> wj = mainInfoVo.getWjList();
                if(!CollectionUtils.isEmpty(wj)){
                    for (int i = 0; i < wj.size(); i++) {
                        pwe.setPath(wj.get(i));
                        productWjService.insertSelective(pwe);
                    }
                }

                //日志信息
                UserEntity user = (UserEntity)this.getBean("user");
                productLogService.savelog(mainInfoVo.getCode(), "新增", "新增了产品主信息，产品：" + mainInfoVo.getChinaName(), user.getName(), user.getCode());

                //4.保存规格信息
                List<ProducFjInfoEntity> specList = vo.getSpecList();
                if(!CollectionUtils.isEmpty(specList)){
                    productFjInfoService.insertSelective(specList.get(0));
                    //日志信息
                    productLogService.savelog(specList.get(0).getProductCode(),"新增","新增产品部件",user.getName(),user.getCode());
                }

                //5.配件保存
                List<ProductFjGeEntity> partsList = vo.getPartsList();
                if(!CollectionUtils.isEmpty(partsList)){
                    for(ProductFjGeEntity parts : partsList){
                        productFjGeService.insertSelective(parts);
                    }
                }

            }

            return R.build(vo);
        } catch (Exception e) {
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }

    /**
     * 获取供应商及供应商最高价信息
     *
     * @param productCode 产品编码
     * @param specCode    规格编码
     * @param vo          回参对象
     */
    private void getSupplierInfo(String productCode, String specCode, ProductMargeInfoVo vo) {
        //获取供应商信息
        ProductFjGysBakExample example = new ProductFjGysBakExample();
        ProductFjGysBakExample.Criteria criteria = example.createCriteria();
        criteria.andProductCodeEqualTo(productCode);
        criteria.andFjCodeEqualTo(specCode);
        List<ProductFjGysBakEntity> productFjGysBakEntities = productFjGysBakService.selectByExample(example);
        if (CollectionUtils.isEmpty(productFjGysBakEntities)) {
            return;
        }
        //初始化集合
        List<SupplierPriceVo> priceVos = new ArrayList<>();
        for (ProductFjGysBakEntity productFjGysBak : productFjGysBakEntities) {
            //初始化对象
            SupplierPriceVo priceVo = new SupplierPriceVo();

            //含税出厂价
            BigDecimal taxIncludedPrice = new BigDecimal("0");
            if (StringUtils.isNotEmpty(productFjGysBak.getCgcb())) {
                taxIncludedPrice = new BigDecimal(productFjGysBak.getCgcb());
            }
            priceVo.setTaxIncludedPrice(taxIncludedPrice);

            //未税出厂价
            BigDecimal untaxedPrice = new BigDecimal("0");
            if (StringUtils.isNotEmpty(productFjGysBak.getCatalog())) {
                untaxedPrice = new BigDecimal(productFjGysBak.getCatalog());
            }
            priceVo.setUntaxedPrice(untaxedPrice);

            //含税FOB价
            BigDecimal taxIncludedFob = new BigDecimal("0");
            if (StringUtils.isNotEmpty(productFjGysBak.getFob())) {
                taxIncludedFob = new BigDecimal(productFjGysBak.getFob());
            }
            priceVo.setTaxIncludedFob(taxIncludedFob);

            //未税FOB价
            BigDecimal untaxedFob = new BigDecimal("0");
            if (StringUtils.isNotEmpty(productFjGysBak.getCshh())) {
                untaxedFob = new BigDecimal(productFjGysBak.getCshh());
            }
            priceVo.setUntaxedFob(untaxedFob);

            priceVos.add(priceVo);
        }
        //原来的供应商信息
        List<ProductFjGysBakEntity> oldSupplierList = vo.getSupplierList();
        //供应商合并
        if(!CollectionUtils.isEmpty(oldSupplierList)){
            oldSupplierList.addAll(productFjGysBakEntities);
            //重新赋值合并后的供应商信息
            vo.setSupplierList(oldSupplierList);
        }else {
            vo.setSupplierList(productFjGysBakEntities);
        }

        //获取 含税出厂价 未税出厂价 含税FOB价 未税FOB价 最高值
        SupplierPriceVo priceVoMax = new SupplierPriceVo();
        //含税出厂价最高值
        BigDecimal taxIncludedPriceMax = priceVos.stream().map(SupplierPriceVo::getTaxIncludedPrice).max((x1, x2) -> x1.compareTo(x2)).get();
        priceVoMax.setTaxIncludedPrice(taxIncludedPriceMax);
        //未税出厂价最高值
        BigDecimal untaxedPriceMax = priceVos.stream().map(SupplierPriceVo::getUntaxedPrice).max((x1, x2) -> x1.compareTo(x2)).get();
        priceVoMax.setUntaxedPrice(untaxedPriceMax);
        //含税FOB价最高值
        BigDecimal taxIncludedFobMax = priceVos.stream().map(SupplierPriceVo::getTaxIncludedFob).max((x1, x2) -> x1.compareTo(x2)).get();
        priceVoMax.setTaxIncludedFob(taxIncludedFobMax);
        //未税FOB价最高值
        BigDecimal untaxedFobMax = priceVos.stream().map(SupplierPriceVo::getUntaxedFob).max((x1, x2) -> x1.compareTo(x2)).get();
        priceVoMax.setUntaxedFob(untaxedFobMax);
        //原来的供应商最高价
        List<SupplierPriceVo> supplierPriceVos = vo.getSupplierPriceVos();
        //添加新的最高价
        if (!CollectionUtils.isEmpty(supplierPriceVos)) {
            supplierPriceVos.add(priceVoMax);
            //重新赋值供应商最高价信息
            vo.setSupplierPriceVos(supplierPriceVos);
        } else {
            //重新赋值供应商最高价信息
            List<SupplierPriceVo> newSupplierPriceVos = new ArrayList<>();
            newSupplierPriceVos.add(priceVoMax);
            vo.setSupplierPriceVos(newSupplierPriceVos);
        }

        return;
    }


    /**
     * 获取合并的规格信息
     *
     * @param vo  回参对象
     * @param req 需要合并的对象信息
     */
    private void getSpecInfo(ProductMargeInfoVo vo, ProductMargeReq req) {
        //初始化规格回参对象集合
        List<ProducFjInfoEntity> specList = new ArrayList<>();
        //根据产品编码获取规格信息
        ProducFjInfoEntity specInfo = getProductFjInfo(req.getProductCode(), req.getSpecCode());
        if (null == specInfo) {
            return;
        }

        //规格说明
        String newSpecDesc = "";
        if (StringUtils.isNotEmpty(specInfo.getGe())) {
            newSpecDesc = specInfo.getGe();
        }

        //中文描述
        String newProductCDesc = "";
        if (StringUtils.isNotEmpty(specInfo.getChinaRemark())) {
            newProductCDesc = specInfo.getChinaRemark();
        }

        //英文描述
        String newProductEDesc = "";
        if (StringUtils.isNotEmpty(specInfo.getEnglishRemark())) {
            newProductEDesc = specInfo.getEnglishRemark();
        }

        //产品净重
        BigDecimal newNetWeight = new BigDecimal("0");
        if (StringUtils.isNotEmpty(specInfo.getCpjz())) {
            newNetWeight = new BigDecimal(specInfo.getCpjz());
        }

        //产品毛重
        BigDecimal newGrossWeight = new BigDecimal("0");
        if (StringUtils.isNotEmpty(specInfo.getCpmz())) {
            newGrossWeight = new BigDecimal(specInfo.getCpmz());
        }

        //规格编码需要拼接在一起
        String newSpecCode = specInfo.getCode() + "(";
        int index = 0;
        //获取选择合并的配件的规格信息
        for (SpecMargeReq specMarge : req.getSpecMargeList()) {
            ProducFjInfoEntity partsSpec = getProductFjInfo(specMarge.getPartsProductCode(), specMarge.getPartsSpec());
            if (null == partsSpec) {
                continue;
            }
            if (0 == index) {
                //第一次
                //规格编码
                newSpecCode = newSpecCode + partsSpec.getCode();
            } else {
                //多个配件之间用-分割
                //规格编码
                newSpecCode = newSpecCode + "-" + partsSpec.getCode();
            }
            index++;

            //规格说明
            if (StringUtils.isNotEmpty(partsSpec.getGe())) {
                if (StringUtils.isEmpty(newSpecDesc)) {
                    //规格说明 直接赋值
                    newSpecDesc = partsSpec.getGe();
                } else {
                    //多个规格说明，以"-"拼接
                    newSpecDesc = newSpecDesc + "-" + partsSpec.getGe();
                }
            }
            //中文描述
            if (StringUtils.isNotEmpty(partsSpec.getChinaRemark())) {
                if (StringUtils.isEmpty(newProductCDesc)) {
                    //中文描述 直接赋值
                    newProductCDesc = partsSpec.getChinaRemark();
                } else {
                    //多个中文描述，以"-"拼接
                    newProductCDesc = newProductCDesc + "-" + partsSpec.getChinaRemark();
                }
            }
            //英文描述
            if (StringUtils.isNotEmpty(partsSpec.getEnglishRemark())) {
                if (StringUtils.isEmpty(newProductCDesc)) {
                    //英文描述 直接赋值
                    newProductEDesc = partsSpec.getEnglishRemark();
                } else {
                    //多个英文描述，以"-"拼接
                    newProductEDesc = newProductEDesc + "-" + partsSpec.getEnglishRemark();
                }
            }
            //产品净重
            if (StringUtils.isNotEmpty(partsSpec.getCpjz())) {
                //多个产品净重相加
                newNetWeight = newNetWeight.add(new BigDecimal(partsSpec.getCpjz()));
            }
            //产品毛重
            if (StringUtils.isNotEmpty(partsSpec.getCpmz())) {
                //多个产品毛重相加
                newGrossWeight = newGrossWeight.add(new BigDecimal(partsSpec.getCpmz()));
            }

        }
        newSpecCode = newSpecCode + ")";
        specInfo.setCode(newSpecCode);
        specInfo.setGe(newSpecDesc);
        specInfo.setChinaRemark(newProductCDesc);
        specInfo.setEnglishRemark(newProductEDesc);
        specInfo.setCpjz(newNetWeight.toString());
        specInfo.setCpmz(newGrossWeight.toString());
        specInfo.setProductCode(vo.getMainInfo().getCode());
        specInfo.setId(null);
        //供应商价格合计
        List<SupplierPriceVo> supplierPriceVos = vo.getSupplierPriceVos();
        if (!CollectionUtils.isEmpty(supplierPriceVos)) {
            //含税出厂价最高值
            BigDecimal taxIncludedPriceMax = new BigDecimal("0");
            //未税出厂价最高值
            BigDecimal untaxedPriceMax = new BigDecimal("0");
            //含税FOB价最高值
            BigDecimal taxIncludedFobMax = new BigDecimal("0");
            //未税FOB价最高值
            BigDecimal untaxedFobMax = new BigDecimal("0");
            for (SupplierPriceVo priceVo : supplierPriceVos) {
                if (StringUtil.isNotEmpty(priceVo.getTaxIncludedPrice())) {
                    taxIncludedPriceMax = taxIncludedPriceMax.add(priceVo.getTaxIncludedPrice());
                }
                if (StringUtil.isNotEmpty(priceVo.getUntaxedPrice())) {
                    untaxedPriceMax = untaxedPriceMax.add(priceVo.getUntaxedPrice());
                }
                if (StringUtil.isNotEmpty(priceVo.getTaxIncludedFob())) {
                    taxIncludedFobMax = taxIncludedFobMax.add(priceVo.getTaxIncludedFob());
                }
                if (StringUtil.isNotEmpty(priceVo.getUntaxedFob())) {
                    untaxedFobMax = untaxedFobMax.add(priceVo.getUntaxedFob());
                }
            }
            specInfo.setCgcb(taxIncludedPriceMax.toString());
            specInfo.setCgcbws(untaxedPriceMax.toString());
            specInfo.setFob(taxIncludedFobMax.toString());
            specInfo.setCshh(untaxedFobMax.toString());
        }

        specList.add(specInfo);
        vo.setSpecList(specList);

        //设置配件对应的规格编码
        for (ProductFjGeEntity parts : vo.getPartsList()) {
            parts.setZhuge(newSpecCode);
            parts.setMainProductCode(vo.getMainInfo().getCode());
        }
        return;
    }

    /**
     * 获取规格信息
     *
     * @param productCode 产品编码
     * @param specCode    规格编码
     * @return 规格信息
     */
    private ProducFjInfoEntity getProductFjInfo(String productCode, String specCode) {
        ProducFjInfoExample example = new ProducFjInfoExample();
        ProducFjInfoExample.Criteria criteria = example.createCriteria();
        criteria.andProductCodeEqualTo(productCode);
        criteria.andCodeEqualTo(specCode);
        List<ProducFjInfoEntity> infoList = productFjInfoService.selectByExample(example);
        if (CollectionUtils.isEmpty(infoList)) {
            return null;
        }
        return infoList.get(0);
    }

    /**
     * 获取图片和文件
     *
     * @param mainInfoVo 回参对象
     * @param codeList   产品编码集合
     */
    private void getImgAndFile(ProductMainInfoVoEntity mainInfoVo, List<String> codeList) {
        //图片
        List<String> img = new ArrayList<>();
        //文件
        List<String> wj = new ArrayList<>();
        //合并后的图片和文件放一起
        for (String code : codeList) {
            //获取图片
            ProductImgExample exampleImg = new ProductImgExample();
            ProductImgExample.Criteria criteria1 = exampleImg.createCriteria();
            criteria1.andProductCodeEqualTo(code);
            List<ProductImgEntity> productImgEntities = productImgService.selectByExample(exampleImg);
            if (!CollectionUtils.isEmpty(productImgEntities)) {
                for (ProductImgEntity imgEntity : productImgEntities) {
                    img.add(imgEntity.getImg());
                }
            }
            //获取文件
            ProducWjExample exampleWj = new ProducWjExample();
            ProducWjExample.Criteria criteria2 = exampleWj.createCriteria();
            criteria2.andProductCodeEqualTo(code);
            List<ProducWjEntity> productWjEntities = productWjService.selectByExample(exampleWj);
            if (!CollectionUtils.isEmpty(productWjEntities)) {
                for (ProducWjEntity wjEntity : productWjEntities) {
                    wj.add(wjEntity.getPath());
                }
            }
        }
        mainInfoVo.setImgList(img);
        mainInfoVo.setWjList(wj);
        mainInfoVo.setImg(JSON.toJSONString(img));
        mainInfoVo.setWj(JSON.toJSONString(wj));

        return;
    }

    /**
     * 获取主产品信息
     *
     * @param id               产品id
     * @param specCode         规格编码
     * @param vo               回参对象
     * @return 主产品信息
     */
    private ProductMainInfoVoEntity getMainInfoVo(Integer id, String specCode, ProductMargeInfoVo vo) {
        ProductMainInfoExample example = new ProductMainInfoExample();
        ProductMainInfoExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(id);
        List<ProductMainInfoEntity> productMainInfoEntities = productMainInfoService.selectByExample(example);
        ProductMainInfoEntity mainInfo = productMainInfoEntities.get(0);
        ProductMainInfoVoEntity mainInfoVo = new ProductMainInfoVoEntity();
        mainInfoVo = mainInfoVo.conver(mainInfo);
        mainInfoVo.setId(null);

        //作为合并后的配件信息
        ProductFjGeEntity parts = new ProductFjGeEntity();
        parts.setProductCode(mainInfo.getCode());
        parts.setFjCode(specCode);
        parts.setCpbl("1");
        parts.setPjbl("1");
        parts.setChinaname(mainInfo.getChinaName());
        parts.setEnglishname(mainInfo.getEnglishName());
        //根据产品编码获取规格信息
        ProducFjInfoEntity specInfo = getProductFjInfo(mainInfo.getCode(), specCode);
        parts.setMz(specInfo.getCpmz());
        parts.setJz(specInfo.getCpjz());
        parts.setTj(specInfo.getTj());

        //更新配件信息
        List<ProductFjGeEntity> partsList = vo.getPartsList();
        List<ProductFjGeEntity> newPartsList = new ArrayList<>();
        newPartsList.add(parts);
        if(!CollectionUtils.isEmpty(partsList)){
            newPartsList.addAll(partsList);
        }
        vo.setPartsList(newPartsList);

        return mainInfoVo;
    }

    /**目
     * 获取产品目录 下所有的目录code
     * @param code
     * @return
     */
    @RequestMapping(value = "getCatalogBycode")
    @ResponseBody
    public  R<List<String>> getCatalogBycode(String code){

       try {
           List<String> list = productCatalogService.queryIdByCode(code);
           return R.build(list);
       }catch (Exception e){
           e.printStackTrace();
           return R.buildError(ResultStatusEnum.ERROR);
       }
    }
    private String conver(String obj){
        if(obj !=null && obj.equals("")){
            return null;
        }else{
            return obj;
        }

    }


    /**
     * 产品详情-分页
     * @param req
     * @return
     */
    @RequestMapping("statistics/productDetailStatisticsListByPage")
    @ResponseBody
    public R productDetailStatistics(productDetailStatisticsReq req){
        try {
            PageInfo<productDetailStatisticsRes> pageInfo=productMainInfoAllService.productDetailStatisticsPage(req);
            return R.build(0,"",pageInfo.getTotal(),pageInfo.getList());
        } catch (Exception e) {
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }

    /**
     * 产品详情--导出Excel
     */
    @GetMapping(value = "productDetailStatisticsExport")
    @ResponseBody
    public R productDetailStatisticsExport(productDetailStatisticsReq req){
        try {
            if (StringUtils.isNotEmpty(req.getProductCatalogCode())){
                List<String> list = productCatalogService.queryIdByCode(req.getProductCatalogCode());
                req.setProductCatalogCode(String.join(",",list));
            }

            JSONObject obj = productMainInfoAllService.productDetailStatisticsExport(req);
            return R.build(obj);
        }catch (Exception e){
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }


    /**
     * 按供应商采购产品情况统计-分页
     * @param req
     * @return
     */
    @RequestMapping("statistics/productGroupDetailStatisticsListByPage")
    @ResponseBody
    public R productDetailStatistics(productGroupDetailStatisticsReq req){
        try {
            PageInfo<productGroupDetailStatisticsRes> pageInfo=productMainInfoAllService.productGroupDetailStatisticsPage(req);
            return R.build(0,"",pageInfo.getTotal(),pageInfo.getList());
        } catch (Exception e) {
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }

    /**
     * 按供应商采购产品情况统计--导出Excel
     */
    @GetMapping(value = "productGroupDetailStatisticsExport")
    @ResponseBody
    public R productDetailStatisticsExport(productGroupDetailStatisticsReq req){
        try {
            JSONObject obj = productMainInfoAllService.productGroupDetailStatisticsExport(req);
            return R.build(obj);
        }catch (Exception e){
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }

    /**
     * 产品采购Top-分页
     *
     * @param req
     * @return
     */
    @RequestMapping("statistics/productPurchaseTopStatisticsListByPage")
    @ResponseBody
    public R productPurchaseTopStatistics(productPurchaseTopStatisticsReq req) {
        try {
            PageInfo<productPurchaseTopStatisticsRes> pageInfo = productMainInfoAllService.productPurchaseTopStatisticsPage(req);
            return R.build(0, "", pageInfo.getTotal(), pageInfo.getList());
        } catch (Exception e) {
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }
    /**
     * 产品采购Top--导出Excel
     */
    @GetMapping(value = "productPurchaseTopStatisticsExport")
    @ResponseBody
    public R productPurchaseTopStatisticsExport(productPurchaseTopStatisticsReq req){
        try {
            JSONObject obj = productMainInfoAllService.productPurchaseTopStatisticsExport(req);
            return R.build(obj);
        }catch (Exception e){
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }


    /**
     * 厂商产品排价-分页
     * @param req
     * @return
     */
    @RequestMapping("statistics/productPriceDetailStatisticsListByPage")
    @ResponseBody
    public R productDetailStatistics(productPriceDetailStatisticsReq req){
        try {
            PageInfo<productPriceDetailStatisticsRes> pageInfo=productMainInfoAllService.productPriceDetailStatisticsPage(req);
            return R.build(0,"",pageInfo.getTotal(),pageInfo.getList());
        } catch (Exception e) {
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }

    /**
     * 厂商产品排价--导出Excel
     */
    @GetMapping(value = "productPriceDetailStatisticsExport")
    @ResponseBody
    public R productDetailStatisticsExport(productPriceDetailStatisticsReq req){
        try {
            JSONObject obj = productMainInfoAllService.productPriceDetailStatisticsExport(req);
            return R.build(obj);
        }catch (Exception e){
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }



    /**
     * 获取登陆用户信息
     * @return 登陆用户信息
     */
    @GetMapping("/getLoginUserInfo")
    @ResponseBody
    public R getLoginUserInfo(){
        try {
            UserEntity user = (UserEntity)this.getBean("user");
            return R.build(user);
        }catch (Exception e){
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }

    /**
     * 停用产品
     */
    @Transactional(rollbackFor = Exception.class)
    @GetMapping("/deactivateProduct")
    @ResponseBody
    public R deactivateProduct(@RequestParam("ids") List<Integer> ids,@RequestParam("codes") List<String> codes){
        try {
            for (int i = 0; i < codes.size(); i++) {
                Integer sNum= stockService.getStockProduct(codes.get(i));
                if (sNum>0){
                    return R.buildError(ResultStatusEnum.SELECT_NUM_NOT_ZERO);
                }
            }


            Integer num=productMainInfoService.deactivateProduct(ids);
            return R.build(num);
        }catch (Exception e){
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }


    /**
     * 产品未录入单价下采购单统计-分页
     * @param req
     * @return
     */
    @RequestMapping("statistics/productNotEnteredPurchaseStatisticsListByPage")
    @ResponseBody
    public R productNotEnteredPurchaseStatistics(productNotEnteredPurchaseStatisticsReq req){
        try {
            PageInfo<productNotEnteredPurchaseStatisticsRes> pageInfo=productMainInfoAllService.productNotEnteredPurchaseStatisticsPage(req);
            return R.build(0,"",pageInfo.getTotal(),pageInfo.getList());
        } catch (Exception e) {
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }

    /**
     * 产品未录入单价下采购单统计--导出Excel
     */
    @GetMapping(value = "productNotEnteredPurchaseExport")
    @ResponseBody
    public R productNotEnteredPurchaseExport(productNotEnteredPurchaseStatisticsReq req){
        try {
            JSONObject obj = productMainInfoAllService.productNotEnteredPurchaseStatisticsExport(req);
            return R.build(obj);
        }catch (Exception e){
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }


    /**
     *
     * 判断该用户是否拥有 产品中心日志供应商区间价格功能显示(CPZXRZGYSQJJG001) 角色
     */
    @RequestMapping("isContainsRoleProduct")
    @ResponseBody
    public R isContainsRoleProduct(){
        try {
            UserEntity user = (UserEntity) this.getBean("user");
            if (user.getRoles().contains("CPZXRZGYSQJJG001")){
                return R.build(true);
            }else {
                return R.build(false);
            }
        } catch (Exception e) {
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }

    }
}
